﻿
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using Newtonsoft.Json;

namespace ProductsWeb
{
    /// <summary>
    /// Summary description for ProductJSON
    /// </summary>
    public class ProductJSON : IHttpHandler
    {
        List<Product> productList;
        public void ProcessRequest(HttpContext context)
        {
            //context.Response.ContentType = "text/html";
            
            //context.Response.Write("<html><body><h1>Hello</h1></body></html>"); 
            context.Response.ContentType = "text/json";
            //getProductListFromAzure();
            ProductListResult result = new ProductListResult();
            result.ProductList = getProductListFromAzure();
            string json = JsonConvert.SerializeObject(result);

            context.Response.Write(json);
        }

        public List<Product> getProductListFromAzure()
        {
            string str_connection = "Server=tcp:yver2m1c9t.database.windows.net,1433;Database=Product;User ID=pongsakorn@yver2m1c9t;Password=wePA8921!@#;Trusted_Connection=False;Encrypt=True;Connection Timeout=30;";
            SqlConnection con = new SqlConnection(str_connection);
            con.Open();
            SqlCommand command = con.CreateCommand();
            command.CommandText = "select ID,ProductName,ProductDescription," +
                "ProductImage, CategoriesID from Products";
            SqlDataReader reader = command.ExecuteReader();
            productList = new List<Product>();
            productList.Clear();
            while (reader.Read())
            {
                string cnd_url = reader.GetString(3).Replace("http://product77.blob.core.windows.net",
                                                                "http://az630315.vo.msecnd.net");
                productList.Add(new Product()
                {
                    ID = reader.GetInt32(0),
                    ProductName = reader.GetString(1),
                    ProductDescription = reader.GetString(2),
                    ProductImage = cnd_url,
                    CategoryID = reader.GetInt32(4)
                });
            }
            con.Close();
            return productList;
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}